package com.yangye.pidoublename.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yangye.picommon.exception.PiException;
import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author yangye
 * @date 2019/9/19
 */
@Service
public class SiChuanServiceImpl implements DoubleNameService {

	@Autowired
	private RestTemplate restTemplate;

	private final String QUERY_URL = "http://scgazwfw.sczwfw.gov.cn/app/api/convenienceServices/getData";

	/**
	 * 参数
	 * {
	 * 	"applyId": "100101",
	 * 	"secretKey": "21yuivfp3atyp5vxm5897lua698foy0m",
	 * 	"serviceType": "cmcx",
	 * 	"personName": "杨野"
	 * }
	 * @param name
	 * @return
	 */
	@Override
	public DoubleNameVo findByName(String name) {
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		JSONObject postData = new JSONObject();
		postData.put("applyId", "100101");
		postData.put("secretKey", "21yuivfp3atyp5vxm5897lua698foy0m");
		postData.put("serviceType", "cmcx");
		postData.put("personName", name);
		String body = restTemplate.postForObject(QUERY_URL, postData, String.class);
		JSONObject resultJson = JSON.parseObject(body);
		if (StringUtils.equals(resultJson.getString("code"), "success")) {
			JSONArray jsonArray = resultJson.getJSONObject("data").getJSONObject("data").getJSONObject("data").getJSONArray("data");
			JSONObject jsonObject = jsonArray.getJSONObject(0);
			Integer total = jsonObject.getInteger("COUNT");
			DoubleNameVo doubleNameVo = new DoubleNameVo();
			doubleNameVo.setProvince(ProvinceEnum.SICHUAN.getName());
			doubleNameVo.setName(name);
			doubleNameVo.setTotal(total);
			return doubleNameVo;
		} else {
			throw new PiException(ProvinceEnum.SICHUAN.getName() + "请求接口失败");
		}
	}
}
